<template>
<highlightjs language="JavaScript" highlightAuto top :code="code" />
</template>
<script>
export default {
  setup () {
    const code = `
    import 'ol/ol.css'
    import { Map, View } from 'ol'
    import Tile from 'ol/layer/Tile'
    import XYZ from 'ol/source/XYZ'

    const state = reactive({
      map: null,
      mapBox: ref(null),
      tian_di_tu_annotation: null, // 天地图文字标注
      tian_di_tu_road_layer: null, // 天地图路网
      zoom: 12,
      minZoom: 10,
      maxZoom: 14
    })

    const init = () => {
      state.tian_di_tu_annotation = new Tile({
        title: '天地图路网',
        source: new XYZ({
          url: 'http://t4.tianditu.com/DataServer?T=vec_w&x={x}&y={y}&l={z}&tk=ab47b4591ab6e07e0530606eca973edd'
        })
      })

      state.tian_di_tu_road_layer = new Tile({
        title: '天地图文字标注',
        source: new XYZ({
          url: 'http://t3.tianditu.com/DataServer?T=cva_w&x={x}&y={y}&l={z}&tk=ab47b4591ab6e07e0530606eca973edd'
        })
      })

      state.map = new Map({
        target: state.mapBox,
        layers: [state.tian_di_tu_annotation, state.tian_di_tu_road_layer],
        view: new View({
          projection: 'EPSG:4326', // 坐标系，有EPSG:4326和EPSG:3857
          center: [116.41400, 39.91500],
          zoom: state.zoom,
          minZoom: state.minZoom,
          maxZoom: state.maxZoom
        })
      })
    }
    // 放大1级
    const zoomIn = () => {
      const view = state.map.getView() // 获取当前视图
      const zoom = view.getZoom() // 获取当前缩放级别
      view.setZoom(zoom + 1)
      state.zoom = view.getZoom()
    }

    // 缩小1级
    const zoomOut = () => {
      const view = state.map.getView()
      const zoom = view.getZoom()
      view.setZoom(zoom - 1)
      state.zoom = view.getZoom()
    }

    onMounted(() => {
      init()
    })
    `
    return {
      code
    }
  }
}
</script>
